// pages/discovery/discovery.js
import { getDraft } from '../../utils/api'
import { getStar } from '../../utils/api'
import { upStar } from '../../utils/api'
import { deStar } from '../../utils/api'
const myopenid = wx.getStorageSync('openid')

Page({

    /**
     * 页面的初始数据
     */
    data: {
      showModal:false,
      conlist:[],
        zan:[],
        user_nickName:"",

      favor_img2: "../../public/discovery-img/good.png",
      favor_img: "../../public/discovery-img/good-fill.png",
        isLoading:false,
        imgUrls: [
            '../../public/discovery-img/枫桥夜泊.jpg',
            '../../public/discovery-img/登高.jpg',
            '../../public/discovery-img/短歌行.jpg',
          ],
          indicatorDots: false,  //是否显示面板指示点
          autoplay: true,      //是否自动切换
          current:0,
          interval: 3000,       //自动切换时间间隔
          duration: 500,       //滑动动画时长
          inputShowed: false,
          inputVal: "",
          title:"",   //题目
          author:'',  //作者
          day:'',     //日期
          hisList:[],  //列表
          item:''       //列表中的随机元素

    },

    //轮播图事件
    swpbind:function(){
      let index = this.data.current
      if(index==0){
        wx.navigateTo({
          url: `../details/details?name=${JSON.stringify('枫桥夜泊 / 夜泊枫江')}&author=张继`
  
        })
      }else if(index==1){
        wx.navigateTo({
          url: `../details/details?name=${JSON.stringify('登高')}&author=杜甫`
  
        })
      }else{
        wx.navigateTo({
          url: `../details/details?name=${JSON.stringify('短歌行')}&author=曹操`
  
        })
      }
    },

    //轮播图改变执行事件
    imgchange:function(e){
      this.setData({
        current:e.detail.current
      })
    },

    //局部刷新
    bindDownLoad:function(){
        setTimeout(()=>{
            this.setData({
                isLoading:false
            })
            this.disStar()
            this.getdraft() // 下拉刷新触发的事件  再次获取投稿列表
            },2000)
    },

    
    //列表诗词详情转跳
    detailpote(e){
      console.log(e);
      let name = e.currentTarget.dataset.name
      let author = e.currentTarget.dataset.author
      wx.navigateTo({
        url: `../details/details?name=${JSON.stringify(name)}&author=${author}`

      })
    },

    //转跳
    jumploading:function(){
        wx.navigateTo({
          url: '../upload/upload',
          success:function(res){
              console.log('跳转成功')
          },
          fail:function(){
              console.log('跳转失败')
          },
        })
    },

    //下拉刷新
    onRefresh:function(){
        //导航条加载动画
        wx.showNavigationBarLoading()
        //loading 提示框
        wx.showLoading({
          title: 'Loading...',
        })
        console.log("下拉刷新啦");

        setTimeout(function () {
          wx.hideLoading();
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();

        }, 1000)

      },

      //获取投稿列表
      getdraft:function(){
        let openid = wx.getStorageSync('openid') 
        getDraft({'openid':openid}).then(res=>{
            res.draftList.map((item)=>{
              if(item.pote){

                item.pote = item.pote.split('/')
              }
            })

            if(res.code ==200){
              this.isGood(this.data.zan,res)  //区分本用户点赞和未点赞
              this.setData({
                conlist:res.draftList.sort(this.sortBy('id',-1))
              })
            }else{
              console.log(err);
            }

        })

      },
      //排序方法
      sortBy:function(attr,rev){
        if( rev==undefined ){ rev=1 }else{ (rev)?1:-1; }
        return function (a,b){
            a=a[attr];
            b=b[attr];
            if(a<b){ return rev*-1}
            if(a>b){ return rev* 1 }
            return 0;
        }
      },

      //点赞功能
      praiseThis: function (e) {
        let index = e.currentTarget.dataset.index

        var that = this;
        for(var i=0;i<that.data.conlist.length;i++){
          if(index == that.data.conlist[i].id){
            var num = that.data.conlist[i].like_nums
            let str = "conlist["+i+"].is_good"
            let str2 = "conlist["+i+"].like_nums"
            if(that.data.conlist[i].is_good ===0){  //本用户没有点赞的情况
              ++num
              that.setData({
                [str]:1,
                [str2]:num
              })
              upStar({id:index,openid:wx.getStorageSync('openid')}).then(res=>{
                console.log(res);
              })
            }else{                                //本用户已经点赞则取消点赞
              --num
              that.setData({
                [str]:0,
                [str2]:num

              })
              deStar({id:index,openid:wx.getStorageSync('openid')}).then(res=>{
                console.log(res);
              })
            }

          }
        }
      },

      //获取点赞信息
      disStar:function(){

        getStar().then(res=>{
          this.setData({
            zan:res.data
          })
        })
      },

      //判断当前用户是否已经点赞
      isGood:function(zan,res){
        if(zan && res.draftList){
          for(var i =0;i<zan.length;i++){
            for(var key in res.draftList){
              if(zan[i].draft_id ==res.draftList[key].id){
        
                res.draftList[key].like_nums ++
                if( zan[i].openid == myopenid){

                  res.draftList[key].is_good = 1
                }

              }

            }
          }

        }
      },

      //转跳评论页面
      disCuss:function(e){
        let item = JSON.stringify(e.currentTarget.dataset.item)
        
        wx.navigateTo({
          url: '../dis-discuss/dis-discuss?item='+encodeURIComponent(item),
          success:function(res){
              console.log('跳转成功')
          },
          fail:function(){
              console.log('跳转失败')
          },
        })
    },

        // 点击取消按钮的回调函数
        modalCancel(e){
          // 这里面处理点击取消按钮业务逻辑
          console.log('点击了取消')
        },
        // 点击确定按钮的回调函数
        modalConfirm(e) {
        // 这里面处理点击确定按钮业务逻辑
          this.setData({
            showModal:!this.data.showModal
          })
        },

        //打开弹窗
        seemodal(){
          let items = this.data.hisList
          let item = items[Math.floor(Math.random()*items.length)];
          this.setData({
            item:item.date + item.title
          })
          this.setData({
            showModal:!this.data.showModal
          })
        },

        //请求接口
        history(){
          var that = this
          wx.request({
            url: 'https://api.oick.cn/lishi/api.php',
            success(res){
              console.log(res.data);
              that.setData({
                day:res.data.day,
                hisList:res.data.result
              })
            }
          })
        },

      

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {



    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      this.disStar()
      this.getdraft()
      this.history()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})